﻿using Microsoft.AspNetCore.Mvc;
using Polly;
using ShoppingCart.Models;
using ShoppingCart.Tools;

namespace ShoppingCart.Controllers
{
    /// <summary>
    /// 购物车相关
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class CartController : ControllerBase
    {
        private readonly RedisService _redisService;

        public CartController(RedisService redisService)
        {
            _redisService = redisService;
        }

        /// <summary>
        ///  获取或创建临时购物车 ID
        /// </summary>
        /// <returns></returns>
        [HttpGet("temp-cart-id")]
        public IActionResult GetOrCreateTempCartId()
        {
            if (!Request.Cookies.TryGetValue("CartId", out var cartId))
            {
                cartId = "62fd984e-3c57-498c-a065-2f9f6f1c3d9b";//Guid.NewGuid().ToString();
                Response.Cookies.Append("CartId", cartId, new CookieOptions
                {
                    Expires = DateTimeOffset.Now.AddDays(7),
                    HttpOnly = true
                });
            }
            return Ok(new { CartId = cartId });
        }

        /// <summary>
        /// 获取购物车内容
        /// </summary>
        /// <param name="cartId">购物车Id</param>
        /// <returns></returns>
        [HttpGet("{cartId}")]
        public async Task<IActionResult> GetCart(string cartId)
        {
            var cart = await _redisService.GetCartAsync(cartId);
            return Ok(cart);
        }

        /// <summary>
        /// 添加商品到购物车
        /// </summary>
        /// <param name="cartId">购物车Id</param>
        /// <param name="item">商品</param>
        /// <returns></returns>
        [HttpPost("{cartId}/add")]
        public async Task<IActionResult> AddToCart(string cartId, [FromBody] CartItem item)
        {
            var cart = await _redisService.GetCartAsync(cartId);
            cart.AddItem(item);  // 添加商品到购物车
            await _redisService.SetCartAsync(cartId, cart);
            return Ok("商品已添加到购物车");
        }

        /// <summary>
        /// 删除购物车中的商品
        /// </summary>
        /// <param name="cartId">购物车Id</param>
        /// <param name="productId">商品Id</param>
        /// <returns></returns>
        [HttpDelete("{cartId}/remove/{productId}")]
        public async Task<IActionResult> RemoveFromCart(string cartId, int productId)
        {
            var cart = await _redisService.GetCartAsync(cartId);
            cart.RemoveItem(productId);  // 从购物车中删除商品
            await _redisService.SetCartAsync(cartId, cart);
            return Ok("商品已从购物车删除");
        }

        /// <summary>
        /// 更新购物车中的商品数量
        /// </summary>
        /// <param name="cartId">购物车Id</param>
        /// <param name="productId">商品Id</param>
        /// <param name="quantity">数量</param>
        /// <returns></returns>
        [HttpPut("{cartId}/update/{productId}")]
        public async Task<IActionResult> UpdateItemQuantity(string cartId, int productId, [FromBody] int quantity)
        {
            var cart = await _redisService.GetCartAsync(cartId);
            cart.UpdateItemQuantity(productId, quantity);  // 更新商品数量
            await _redisService.SetCartAsync(cartId, cart);
            return Ok("商品数量已更新");
        }

        /// <summary>
        /// 获取购物车总价
        /// </summary>
        /// <param name="cartId">购物车Id</param>
        /// <returns></returns>
        [HttpGet("{cartId}/total-price")]
        public async Task<IActionResult> GetTotalPrice(string cartId)
        {
            var cart = await _redisService.GetCartAsync(cartId);
            var totalPrice = cart.GetTotalPrice();
            return Ok(new { TotalPrice = totalPrice });
        }

        /// <summary>
        /// 合并临时购物车和登录后的购物车
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
        [HttpPost("merge/{userId}")]
        public async Task<IActionResult> MergeCarts(string userId)
        {
            // 确保 Request.Cookies 不为 null
            if (Request.Cookies == null || !Request.Cookies.TryGetValue("CartId", out var tempCartId) || string.IsNullOrEmpty(tempCartId))
                return BadRequest("未找到临时购物车");

            var tempCart = await _redisService.GetCartAsync(tempCartId);
            if (!tempCart.Items.Any())
                return BadRequest("临时购物车为空");

            var userCart = await _redisService.GetCartAsync(userId);
            foreach (var item in tempCart.Items)
            {
                userCart.AddItem(item);  // 合并商品
            }

            await _redisService.SetCartAsync(userId, userCart);
            await _redisService.DeleteCartAsync(tempCartId);

            // 删除 Cookie
            Response.Cookies.Delete("CartId");

            return Ok("购物车已合并");
        }

        /// <summary>
        /// 用户签到
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPost("{userId}/SignIn")]
        public async Task<IActionResult>  SignIn(int userId)
        {
            var signInNumber = await _redisService.GetNextSignInNumber();

            // 将签到记录插入数据库，包含 userId 和 signInNumber,次数省略

            return Ok(new { userId = userId,signInNumber = signInNumber,sinnInDate = DateTime.Now });
        }

        /// <summary>
        /// 用户签到
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPost("{userId}/SignInCheck")]
        public async Task<IActionResult> SignInCheck(int userId)
        {
            var canSignIn = await _redisService.CanUserSignInToday(userId);

            // 如果返回 false，表示用户今天已经签到过
            if (!canSignIn)
            {
                throw new InvalidOperationException("今天已经签到了");
            }

            // 获取下一个签到号
            var signInNumber = await _redisService.GetNextSignInNumber();

            // 将签到记录保存到数据库


            // 将签到记录插入数据库，包含 userId 和 signInNumber,次数省略

            return Ok(new { userId = userId, signInNumber = signInNumber, sinnInDate = DateTime.Now });
        }
    }

}
